package cn.yzking.studentmanagement;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import com.google.android.material.datepicker.MaterialDatePicker;

import java.text.SimpleDateFormat;
import java.util.Locale;

import cn.yzking.studentmanagement.databinding.ActivityStudentDetailBinding;
import cn.yzking.studentmanagement.utils.MyDBHelper;

public class StudentDetailActivity extends AppCompatActivity {
    private boolean update;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityStudentDetailBinding binding = ActivityStudentDetailBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        MaterialDatePicker<Long> datePicker = MaterialDatePicker.Builder.datePicker()
                .setTitleText("选择出生日期")
                .setSelection(MaterialDatePicker.todayInUtcMilliseconds())
                .setInputMode(MaterialDatePicker.INPUT_MODE_TEXT)
                .build();
        datePicker.addOnPositiveButtonClickListener(selection -> {
            // 时间戳转换
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", Locale.SIMPLIFIED_CHINESE);
            String dateString = formatter.format(selection);
            binding.etBirthday.setText(dateString);
        });

        binding.etBirthday.setOnClickListener(v -> datePicker.show(getSupportFragmentManager(), "tag"));
        
        String id = getIntent().getStringExtra("id");
        String name = getIntent().getStringExtra("name");
        String phone = getIntent().getStringExtra("phone");
        String sex = getIntent().getStringExtra("sex");
        String birthday = getIntent().getStringExtra("birthday");
        binding.etId.setText(id);
        binding.etName.setText(name);
        binding.etPhone.setText(phone);
        binding.tvSex.setText(sex);
        binding.etBirthday.setText(birthday);

        this.update = false;
        binding.buttonUpdate.setOnClickListener(v -> {
            if (this.update) {
                MyDBHelper helper = new MyDBHelper(this);
                helper.updateStudent(binding.etId.getText().toString(), binding.etName.getText().toString(), binding.etPhone.getText().toString(), binding.tvSex.getText().toString(), binding.etBirthday.getText().toString());
                binding.buttonUpdate.setText("修改");
                binding.tilName.setEnabled(false);
                binding.tilPhone.setEnabled(false);
                binding.tvSex.setEnabled(false);
                binding.tilBirthday.setEnabled(false);
            } else {
                binding.buttonUpdate.setText("确认修改");
                binding.tilName.setEnabled(true);
                binding.tilPhone.setEnabled(true);
                binding.tvSex.setEnabled(true);
                binding.tilBirthday.setEnabled(true);
            }
            this.update = !this.update;
        });
    }
}